package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Description: 套餐预约
 * @Author: HuChunping
 * @Date: 2021/01/16
 **/
@RestController
@RequestMapping("/order")
public class OrderController {
    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * @Description: 微信端用户预约套餐，并返回id供跳转后查询展示预约信息
     * @Author: HuChunPing
     * @Date: 2021/1/16 21:55
     * @param orderInfo: 前端传的体检人信息数据，用map封装
     * @return: com.itheima.health.entity.Result
     **/
    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> orderInfo){
        // 从jedispool池中获取一个连接
        Jedis jedis = jedisPool.getResource();
        // 拼接该号码的jedis的key
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + orderInfo.get("telephone");
        // 该key在redis中的值
        String codeInRedis = jedis.get(key);
        log.info("codeInRedis:{}",codeInRedis);
        // 如果redis不存在这个key
        if (StringUtils.isEmpty(codeInRedis)){
            return new Result(false, "请重新获取验证码");
        }
        log.info("codeFromUI:{}",orderInfo.get("validateCode"));
        // 存在key
        // 获取用户输入的验证码
        String validateCode = orderInfo.get("validateCode");
        // 判断验证码是否正确
        // 如果验证码不正确
        if (!codeInRedis.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        // 验证码正确
        // 删除redis中的验证码,避免用户重复使用此验证码提交,(测试时可以不用)
        jedis.del(key);
        jedis.close();
        // 设置预约类型，用于区分微信预约与后台操作的电话预约
        orderInfo.put("orderType",Order.ORDERTYPE_WEIXIN);
        // 成功预约，传给前端预约用户id，前端展示预约信息需要预约id
        Order order = orderService.submitOrder(orderInfo);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order);
    }

    /**
     * 查询预约订单信息
     * @Author: HuChunping
     * @Date: 2021/1/17 21:51
     * @param id:订单id
     * @return: com.itheima.health.entity.Result
     **/
    @GetMapping("/findById")
    public Result findById(int id){
        Map<String,String> orderInfo = orderService.findById(id);
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, orderInfo);
    }
}
